package com.example.administrator.im.utils;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.im.MyApplication;
import com.example.administrator.im.R;
import com.example.administrator.im.db.FriendDBHelper;
import com.example.administrator.im.ui.activity.ChatRoomActivity;
import com.hyphenate.chat.EMMessage;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import static android.app.Notification.DEFAULT_ALL;

/**
 * create:2018/9/26 11:37
 * author: 姚鸿杰
 **/
public class NotificationUtils {

    private static final String TAG = "NotificationUtils";
    private static NotificationManager notifyManager;

    public static final String CHAT_CHANNEID = "chat";
    public static final String CHAT_CHANNENAME = "聊天消息";
    public static final int CHAT_IMPORTANCE = NotificationManager.IMPORTANCE_HIGH;

    public static final String SUBSCRIBE_CHANNEID = "subscribe";
    public static final String SUBSCRIBE_CHANNENAME = "订阅消息";
    public static final int SUBSCRIBE_IMPORTANCE = NotificationManager.IMPORTANCE_DEFAULT;


    /**
     * 获取通知管理器
     *
     * @return 获取通知管理器
     */
    private static NotificationManager getNotifyManager() {
        if (notifyManager != null) {
            return notifyManager;
        }
        return notifyManager = (NotificationManager) MyApplication.getmContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);
    }

    /**
     * 客户端发起通知
     *
     * @param msg       消息
     * @param channeId  什么类型
     * @param isSuspend 是否悬浮
     */
    public static void sendNotification(EMMessage msg, String channeId, boolean isSuspend, boolean shock, boolean led) {

        String username = msg.getUserName();
        String nickname = msg.getUserName();
        int id = 1;
        FriendDBHelper friend = LitePal.where("username = ?", msg.getUserName()).findFirst(FriendDBHelper.class);
        if (friend != null) {
            nickname = TextUtils.isEmpty(friend.getRemarks()) ? friend.getNickname() : friend.getRemarks();
            id = friend.getId();
        }

        int what = msg.getIntAttribute("type", -1);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            sendNotification(id, username, nickname, HttpUtils.PORT + friend.getImg_path(),
                    what == EMUtils.IMAGE ? "[图片]" : EMUtils.getContent(msg), channeId, shock, led);
        } else {
            sendNotification(id, username, nickname, HttpUtils.PORT + friend.getImg_path(),
                    what == EMUtils.IMAGE ? "[图片]" : EMUtils.getContent(msg), isSuspend, shock, led);
        }
    }

    /**
     * @param path     发送者头像路径
     * @param mContext
     * @return 返回bitmap
     */
    private static Bitmap getBitmap(String path, Context mContext) {

        Bitmap bitmap = null;
        if (TextUtils.equals(path, HttpUtils.PORT)) {
            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.login_logo);
        } else {
            try {
                bitmap = Glide.with(mContext).asBitmap().load(path).submit(150, 150).get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    /**
     * 发送通知
     *
     * @param title    发送者对象
     * @param content  发送内容
     * @param channeId 什么类型
     */
    @TargetApi(Build.VERSION_CODES.O)
    private static void sendNotification(int id, String username, String title, String path, String content, String channeId
            , boolean shock, boolean led) {
        Context mContext = MyApplication.getmContext();
        //获取NotificationManager实例
        NotificationManager notifyManager = getNotifyManager();
        Bitmap bitmap = Bitmap.createBitmap(getBitmap(path, mContext));

        //实例化NotificationCompat.Builde并设置相关属性
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, channeId)
                .setLargeIcon(transform(bitmap))  //图标带修改为联系人头像
                //设置小图标
                .setSmallIcon(R.mipmap.login_logo)
                //设置通知标题
                .setContentTitle(title)
                //设置通知内容
                .setContentText(content)
                //设置通知时间，默认为系统发出通知的时间，通常不用设置
                .setWhen(System.currentTimeMillis())
                //点击后消失
                .setAutoCancel(true)
                //跳转到那个activity
                .setContentIntent(getPendingIntent(username, title))
                .setDefaults(getDefault(shock, led));
        //通过builder.build()方法生成Notification对象,并发送通知,id=1
        notifyManager.notify(id, builder.build());   //扩展消息则把1改掉
    }

    /**
     * 发送通知
     *
     * @param title     发送者对象
     * @param content   发送内容
     * @param isSuspend 是否悬浮
     */
    private static void sendNotification(int id, String username, String title, String path, String content, boolean isSuspend
            , boolean shock, boolean led) {
        Context mContext = MyApplication.getmContext();
        //获取NotificationManager实例
        NotificationManager notifyManager = getNotifyManager();
        Bitmap bitmap = Bitmap.createBitmap(getBitmap(path, mContext));

        //实例化NotificationCompat.Builde并设置相关属性
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
                .setLargeIcon(transform(bitmap))
                //设置小图标
                .setSmallIcon(R.mipmap.login_logo)
                //设置通知标题
                .setContentTitle(title)
                //设置通知内容
                .setContentText(content)
                //点击后消失
                .setAutoCancel(true)
                //设置通知时间，默认为系统发出通知的时间，通常不用设置
                .setWhen(System.currentTimeMillis())
                //跳转到那个activity
                .setContentIntent(getPendingIntent(username, title));
        //通过builder.build()方法生成Notification对象,并发送通知,id=1
        if (isSuspend) {
            builder.setDefaults(getDefault(shock, led));
            builder.setPriority(Notification.PRIORITY_HIGH);
        }
        notifyManager.notify(id, builder.build());
    }


    private static int getDefault(boolean shock, boolean led) {
        int flag = 0;
        if (shock || led) {
            if (shock && led) {
                flag = Notification.DEFAULT_ALL;
            } else if (shock) {
                flag = Notification.DEFAULT_VIBRATE;
            } else {
                flag = Notification.DEFAULT_LIGHTS;
            }
        } else {
            flag = Notification.DEFAULT_SOUND;
        }
        return flag;
    }

    //图片化圆
    private static Bitmap transform(Bitmap source) {
        int size = Math.min(source.getWidth(), source.getHeight());

        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
        if (squaredBitmap != source) {
            source.recycle();
        }

        Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        paint.setShader(shader);
        paint.setAntiAlias(true);

        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);

        squaredBitmap.recycle();
        return bitmap;
    }

    /**
     * 清除全部通知
     */
    public static void cancelAllNotify() {
        if (notifyManager == null) {
            return;
        }
        notifyManager.cancelAll();
    }

    /**
     * 点击消息后跳转到那个页面
     *
     * @param account 发送者的账号
     * @return PendingIntent
     */
    private static PendingIntent getPendingIntent(String account, String nickname) {
        Intent intent = new Intent(MyApplication.getmContext(), ChatRoomActivity.class);
        intent.putExtra("username", account);
        intent.putExtra("nickname", nickname);
        PendingIntent pendingIntent = PendingIntent.getActivity(MyApplication.getmContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        return pendingIntent;
    }

    /**
     * 媒体
     *
     * @param context   上下文
     * @param time      震动时长
     * @param mediaPath 提示音路径
     */
    public static void setMedia(Context context, long time, String mediaPath) {
        if (time != 0) {
            Vibrator vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
            vibrator.vibrate(time);
        }

        if (mediaPath != null) {
            try {
                AssetFileDescriptor fileDescriptor = context.getAssets().openFd(mediaPath);
                MediaPlayer mp = new MediaPlayer();
                mp.reset();
                mp.setDataSource(fileDescriptor.getFileDescriptor(),
                        fileDescriptor.getStartOffset(), fileDescriptor.getLength());
                mp.prepare();   //准备工作
                mp.start(); //开始播放
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
